<?php

namespace App\Http\Controllers;

// require_once('/sdk/youpaiyun-sdk/vendor/autoload.php');
// require_once('/sdk/youpaiyun-sdk/upyun_config.php');

use Illuminate\Http\Request;
use App\Models\LoginUser;
use App\Models\SoftGoods;
use App\Models\Config;
use App\Models\Friends;
use App\Models\Navbar;
use Storage;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    //登录
    public function login(Request $request){
        $L_username = $request -> input('L_username');
        $L_pass = $request -> input('L_pass');
        $users = LoginUser::where('username',$L_username)->get()->first();
        // dd($users);
        if($users){
            if($users['password'] == $L_pass){
                $data = array('status' => 0, 'msg' => '登录成功！');
            }else{
                $data = array('status' => 1, 'msg' => '密码错误！');
            }
        }else{
            $data = array('status' => 1, 'msg' => '不存在这个用户！');
        }
        $request->session()->put('user', $users);
        return response()->json($data);
    }
    //待发送商品页
    public function index(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        // dd('昵称是：'.$nickname);
        return view('user.list',['navbar'=>$navbar , 'id'=>0 , 'nickname'=>$nickname]);
    }
    //已发送商品页
    public function send(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.send',['navbar'=>$navbar , 'id'=>1 , 'nickname'=>$nickname]);
    }
    //添加商品页面
    public function add(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.add',['navbar'=>$navbar , 'id'=>2 , 'nickname'=>$nickname]);
    }
    //添加商品数据到数据库
    public function goods_add(Request $request){
        $data = $request -> all();
        // dd($data);
        $count = count($data['img']);
        $goodsImage = $sucai1 = $sucai2 = $sucai3 = $upcment = '';
        for ($i=0; $i<$count; $i++)
        {
           switch ($i) {
              case 0:
                $goodsImage=$data['img'][0];
                break;
              case 1:
                $sucai1=$data['img'][1];
                break;
              case 2:
                $sucai2=$data['img'][2];
                break;
              case 3:
                $sucai3=$data['img'][3];
                break;
           }
        }
        if(isset($data['upcment']))
        {
        	$upcment = $data['upcment'];
        }
        $id = SoftGoods::create([
            'status' => 0,
            'goodsImage' => $goodsImage,
            'sucai1' => $sucai1,
            'sucai2' => $sucai2,
            'sucai3' => $sucai3,
            'docment' => $data['docment'],
            'upcment' => $upcment,
            'in_time' => date("Y-m-d H:i:s"),
            'username' => session()->get('user')->username
        ]);
        if ($id){
            // dd($id);
            SoftGoods::where('id',$id->ID) -> update(['index' => $id->ID]);
        	$return['code']  = 0;
        	$return['id']  = $id;
        	$return['msg']  = "推送成功";
        	}
        else{
            // echo 'insert failed: ' . $db->getLastError();
        	$return['code']  = 1;
        	$return['id']  = $id;
        	$return['msg']  = 'insert failed: ' . SoftGoods -> getLastError();
        	}
        return json_encode($return,JSON_UNESCAPED_UNICODE);
    }
    //list接口
    public function get_list(Request $request){
        $status = $request->input('status');
        $username = $request->session()->get('user');
        $username = $username['username'];
        $soft = SoftGoods::where('username',$username)->where('status',$status)->orderBy('index', 'asc')->get();//数组array
        $softs = array();
        $softs['data'] = $soft;
        $softs['count'] = count($soft);
        $softs['code'] = 0;
        return json_encode($softs);
    }
    //上传文件接口
    public function upload_img(Request $request){
        $file = $request -> file('file');    //获取文件名称
        $file_name = date('Y-m-d-H-i-s', time())."_".$file->getClientOriginalName();

        // 上传文件
        $res = $file->move('./uploads/images',$file_name);////上传到本地服务器
        $base_url = 'http://'.$request->server('HTTP_HOST').'/uploads/images/';//上传到本地服务器
        // $res = uploadImg($file_name,$file->getRealPath());;////上传到oss
        if(empty($res)){
        	$return['msg'] = "上传失败";
        	$return['code'] = 1;
        	$return['file_name'] = $file_name;
        	$return['res'] = $res;

        }else{
        	$return['msg'] = "上传成功";
        	$return['code'] = 0;
        	$return['file_name'] = $file_name;
        	$return['img_url'] = $base_url.$file_name;
        	$return['res'] = $res;
        }

        return json_encode($return);
    }
    //退出登录
    public function logout(){
        session()->flush();
        return redirect('/user/login');
    }
    //识别主图
    public function discern_img(Request $request){
        $str = $request->getContent();
        // dd($data);
        preg_match_all('%https?:\/\/.*?\s%is',$str,$arr);//能匹配到优惠券地址
        //遍历取优惠券
        $num = count($arr[0]);
        $longurl_arr = array();
        $shorturl_arr = array();
        for($i=0; $i < $num; $i++){
        	if(strstr($arr[0][$i], 'coupon')){
        		 $longurl=$arr[0][$i];
        		 $longurl = str_replace("\n","",$longurl);
        		 $longurl = str_replace("\r","",$longurl);
        		 array_push($longurl_arr,$longurl);
        		 $shorturl = mtw_url($longurl);
        		 array_push($shorturl_arr,$shorturl);
        	}

        }
        if(count($shorturl_arr) > 0){
        	$return['docment']  = str_replace($longurl_arr , $shorturl_arr , $str);
        }else{
            $return['docment']  = $str;
        }
        //遍历取u.jd.com
        preg_match_all("/https:[\/]{2}[a-z]+[.]{1}[a-z\d\-]+[.]{1}[a-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]*/",$str,$arr);
        //匹配不到优惠券地址，如果匹配不到u.jd.com就用这个匹配,提取主图
        $num = count($arr[0]);
        for($i=0; $i < $num; $i++){
        	if(strstr($arr[0][$i], 'u.jd.com')){

        			 $url = $arr[0][$i];
        			 $url = str_replace("\n","",$url);

        			 $resp = UnionOpenGoodsQueryRequest($url);

        			 $arry = json_decode($resp,true);
        			 // var_dump($arry);
        			 if(count($arry['data'])==1){
                        $return['code']  = 0;
        				$return['imgurl'] = $arry['data'][0]['imageInfo']['imageList'][0]['url'];
        				$return['msg']  = "提取成功";
        				break;
        			 }else{
                         $return['code']  = 1;
        				 $return['msg']  = "主图提取失败，请检查推广链接";
        			 }


        	}
        }
        $return['url']  = $url;
        $return['longurl']  = $longurl_arr;
        $return['shorturl']  = $shorturl_arr;
        $return['url_count']  = count($shorturl_arr);
        echo json_encode($return,JSON_UNESCAPED_UNICODE);
    }
    public function daka(){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.daka',['navbar'=>$navbar , 'id'=>3 , 'nickname'=>$nickname]);
    }
    public function daka_list(Request $request){
        if($request->hasfile('start')){$start=$request->get('start');}else{$start="0";}
        if($request->hasfile('limit')){$limit=$request->get('limit');}else{$limit="40";}
        if($request->hasfile('category')){$category=$request->get('category');}else{$category="";}
        if($request->hasfile('iconId')){$iconId=$request->get('iconId');}else{$iconId="";}

        $res = curl_get_https("http://m.dakabl.com/goods/list1.htm?start=".$start."&limit=".$limit."&category=".$category."&iconId=".$iconId);
        $res = str_replace('>一键推广<',' onclick="tg_btn(this)">一键推送<',$res);
        return $res;
    }
    public function daka_goods_add(Request $request){
        $daka_id = $request->input('id');
        // dd($daka_id);
        $res = curl_get_https("http://www.dakajd.com/api/recommend?userId=3847&appId=10008&nonceStr=1531470218&sign=26eaf977a06d34e801e8debf5417a927&id=".$daka_id);
        $json_str = json_decode($res , true);//json字符串转成array

        $docment = $json_str['data']['docment'];
        $docment = base64_encode($docment);
        $goodsImage = $json_str['data']['goodsImage'];
        $goodsImage = str_replace('_s','_o',$goodsImage);

        //插入到数据库
        $id = SoftGoods::create([
            'status' => 0,
            'goodsImage' => $goodsImage,
            'sucai1' => '',
            'sucai2' => '',
            'sucai3' => '',
            'docment' => $docment,
            'upcment' => '',
            'in_time' => date("Y-m-d H:i:s"),
            'username' => session()->get('user')->username
        ]);
        if ($id){
            // dd($id);
            SoftGoods::where('id',$id->ID) -> update(['index' => $id->ID]);
        	$return['code']  = 0;
        	$return['id']  = $id;
        	$return['msg']  = "推送成功";
        	}
        else{
            // echo 'insert failed: ' . $db->getLastError();
        	$return['code']  = 1;
        	$return['id']  = $id;
        	$return['msg']  = '推送失败，insert failed: ' . SoftGoods -> getLastError();
        	}
        return json_encode($return,JSON_UNESCAPED_UNICODE);
    }
    public function iframe(Request $request){
        $ID = $request -> get("ID");
        // dd($ID);
        $data = SoftGoods::where("ID",$ID)->first();
        // dd($data->docment);
        return view('user.edit',['data'=>$data]);
    }
    //修改商品
    public function edit(Request $request){
        $data = $request -> all();
        // dd($data);
        $count = count($data['img']);
        $goodsImage = $sucai1 = $sucai2 = $sucai3 = $upcment = '';
        for ($i=0; $i<$count; $i++)
        {
           switch ($i) {
              case 0:
                $goodsImage=$data['img'][0];
                break;
              case 1:
                $sucai1=$data['img'][1];
                break;
              case 2:
                $sucai2=$data['img'][2];
                break;
              case 3:
                $sucai3=$data['img'][3];
                break;
           }
        }
        if(isset($data['upcment']))
        {
        	$upcment = $data['upcment'];
        }
        $return['code']  = 0;
        $return['id']  = $data['ID'];
        $return['msg']  = "修改商品成功";
        try {
               SoftGoods::where('id',$data['ID']) -> update([
                       'goodsImage' => $goodsImage,
                       'sucai1' => $sucai1,
                       'sucai2' => $sucai2,
                       'sucai3' => $sucai3,
                       'docment' => $data['docment'],
                       'upcment' => $upcment,
                   ]);//update返回更新条数
            } catch (QueryException $e) {
                $return['code']  = 1;
                $return['id']  = $data['ID'];
                $return['msg']  = '修改商品失败->insert failed: ' . $e->getMessage();
                // dd($e->getMessage());

            }

        return json_encode($return,JSON_UNESCAPED_UNICODE);
    }
    //排序
    public function goods_list_order(Request $request){
        $order = $request -> get('order');
        $ID = $request -> get('ID');
        // $order = $request -> all();
        // dd($order);
        $return['code']  = 0;
        $return['id']  = $ID;
        $return['msg']  = "成功";
        switch ($order){
            case 'del':
                // echo '下架';
                try{
                    SoftGoods::find($ID)->update(['status'=>3]);
                }catch(QueryException $e){
                    $return['code']  = 1;
                    $return['id']  = $ID;
                    $return['msg']  = '失败->insert failed: ' . $e->getMessage();
                }
                break;
            case 'top':
                // echo '置顶';
                $soft = SoftGoods::where('status',0)->orderBy('index', 'asc')->first();
                $index = $soft['index']-1;
                try{
                    SoftGoods::find($ID)->update(['index'=>$index]);
                }catch(QueryException $e){
                    $return['code']  = 1;
                    $return['id']  = $ID;
                    $return['msg']  = '失败->insert failed: ' . $e->getMessage();
                }
                break;
            case 'page-up':
                $index = $request -> get('index');
                //查询上一条的商品数据
                $soft = SoftGoods::where('index','<',$index)->where('status',0)->orderBy('index', 'DESC')->first();
                // dd($soft);
                SoftGoods::where('ID',$ID)->update([
                    'index'=>$soft['index']
                ]);
                SoftGoods::where('ID',$soft['ID'])->update([
                    'index'=>$index
                ]);
                // echo '上移';
                break;
            case 'page-down':
                // echo '下移';
                $index = $request -> get('index');
                //查询下一条的商品数据
                $soft = SoftGoods::where('index','>',$index)->where('status',0)->orderBy('index', 'asc')->first();
                SoftGoods::where('ID',$ID)->update([
                    'index'=>$soft['index']
                ]);
                SoftGoods::where('ID',$soft['ID'])->update([
                    'index'=>$index
                ]);
                break;
        }
        return json_encode($return,JSON_UNESCAPED_UNICODE);

    }
    public function fd(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.fd',['navbar'=>$navbar , 'id'=>4 , 'nickname'=>$nickname]);
    }
    public function get_friends(Request $request){
        $status = $request -> get('status');
        $username = session()->get('user')->username;
        $friends = Friends::get();//array title value
        $values = [];
        $friend = [];
        $data = [];
        if($status == 'fd'){
            $config = Config::where('status',1)->where('Username',$username)->get();
            foreach($friends as $k=>$v){
                $friend[$k]['title'] = base64_decode($v['nickname']);
                $friend[$k]['value'] = $k + 1;
                $friend[$k]['wxid'] = $v['wxid'];
                if(strpos(strval($config),$v['wxid']) !== false){
                    $values[] = $k + 1;
                }
            }
            $data['friends'] = $friend;
            $data['values'] = $values;
        }elseif($status == 'cj'){
            $config = Config::where('status',2)->where('Username',$username)->get();
            foreach($friends as $k=>$v){
                $friend[$k]['title'] = base64_decode($v['nickname']);
                $friend[$k]['value'] = $k + 1;
                $friend[$k]['wxid'] = $v['wxid'];
                if(strpos(strval($config),$v['wxid']) !== false){
                    $values[] = $k + 1;
                }
            }
            $data['friends'] = $friend;
            $data['values'] = $values;
        }elseif($status == 'pi'){
            $config = Config::where('status',1)->where('Username',$username)->get();
            foreach($config as $k=>$v){
                $config[$k]['nickname'] = base64_decode($v['nickname']);
            }
            $data['code'] = 0;
            $data['count'] = count($config);
            $data['data'] = $config;
        }

        // dd($status);
        return $data;
    }
    public function fconfig(Request $request){
        $status = $request->get('status');
        $input = $request->post();
        // dd($input[3]['title']);
        $username = session()->get('user')->username;
        if($status == 'fd'){
            Config::where('Username',$username)->where('status',1)->delete();
            $data = [];
            $tmp = [];
            foreach($input as $k=>$v){
                $tmp['wxid'] = $v['wxid'];
                $tmp['nickname'] = Base64_encode($input[$k]['title']);
                $tmp['status'] = 1;
                $tmp['Username'] = $username;
                $data[] = $tmp;
            }
            // dd($data);
            $userData = Config::insert($data);//返回布尔值
            // dd($userData);
            if($userData){
                $res["code"] = 0;
            }else{
                $res["code"] = 1;
            }
        }elseif($status == 'cj'){
            Config::where('Username',$username)->where('status',2)->delete();
            $data = [];
            $tmp = [];
            foreach($input as $k=>$v){
                $tmp['wxid'] = $v['wxid'];
                $tmp['nickname'] = Base64_encode($input[$k]['title']);
                $tmp['status'] = 2;
                $tmp['Username'] = $username;
                $data[] = $tmp;
            }
            // dd($data);
            $userData = Config::insert($data);//返回布尔值
            // dd($userData);
            if($userData){
                $res["code"] = 0;
            }else{
                $res["code"] = 1;
            }
        }elseif($status == 'pc'){
            // $input = $request->only(['wxid', 'PositionId', 'Username']);
            // $input = $request->post();
            // dd($input);
            $sql = "update config set PositionId = case ";
            foreach($input as $k=>$v){
                $sql .= "when wxid= '".$v['wxid']."' then '".$v['PositionId']."' " ;
                if($k == 0){
                    $wxid = "'".$v['wxid']."'";
                }else{
                    $wxid .= ",'".$v['wxid']."'";
                }
            }
            $sql .= "end where wxid in"."(".$wxid.") and Username='".$input[0]['Username']."'";
            // dd($sql);
            $upres = DB::update($sql);
            if($upres){
                $res["code"] = 0;
            }else{
                $res["code"] = 1;
                $res["msg"] = "设置推广位失败";
            }
        }

        return response()->json($res);

    }
    public function cj(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.cj',['navbar'=>$navbar , 'id'=>5 , 'nickname'=>$nickname]);
    }
    public function position(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.position',['navbar'=>$navbar , 'id'=>6 , 'nickname'=>$nickname]);
    }
    public function config(Request $request){
        $navbar = Navbar::get();
        $nickname = session()->get('user')->nickname;
        return view('user.config',['navbar'=>$navbar , 'id'=>7 , 'nickname'=>$nickname]);
    }

    public function test(){
        // $res = UnionOpenGoodsQueryRequest("https://u.jd.com/HMHrZXK");
        $res = promotion_byunionid_get(1000130713,10086,'https://u.jd.com/RCVbMHC');
        // "{"code":2001906,"message":"优惠券已过期","requestId":"o_0b12805e_l6tfhzm3_290674698"}"
        // "{"code":200,"data":{"shortURL":"https://u.jd.com/RCVaGNY"},"message":"success","requestId":"o_0b648122_l6tfivi0_251701621"}"
        dd($res);

    }
    public function get_qj_config(Request $request){
        $username = session()->get('user')->username;
        $res = LoginUser::where('username',$username)->get(['UnionId','start_time','end_time','fd_status','room_desc','at_time','goods_rest','img_rest'])->first();
        return response()->json($res);
    }
    public function write_config(Request $request){
        $input = $request->all();
        $username = session()->get('user')->username;
        // dd($input);
        $fd_time_arry = explode("-" , $input["fd_time"]);
        $data['start_time'] = trim($fd_time_arry[0]);
        $data['end_time'] = trim($fd_time_arry[1]);
        $data['UnionId'] = (int)$input['UnionId'];
        $data['at_time'] = (int)$input['at_time'];
        $data['goods_rest'] = (int)$input['goods_rest'];
        $data['img_rest'] = (int)$input['img_rest'];
        $data['room_desc'] = base64_encode($input['desc']);
        if($input["fd_close"] = "on")
        	$data['fd_status'] = 1;//发单状态,0关，1开
        else
        	$data['fd_status'] = 0;//发单状态,0关，1开
        // dd($data);
        $upres = LoginUser::where('username',$username)->update($data);
        if($upres){
            $res['code'] = 0;
        }else{
            $res['code'] = 1;
        }
        return response()->json($res);

    }



}
